<?php

use Core\API_Controller;
use Libraries\Mail;
use Models\User;

class ForgotController extends API_Controller
{
	// 重置密码
	public function index()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_rules('email', '电子邮箱', 'required|regex_match[/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]{2,4}$/]')
			->set_rules('validateCode', 'required', [
				'required',
				['validate', function ($val) {
					if ($this->session->forgotValidateCode == $val) {
						return true;
					} else {
						$this->form_validation->set_message('validate', '验证码不正确');
						return false;
					}
				}]
			])
			->set_rules('newPassword', '新密码', 'required|min_length[6]');
		if ($this->form_validation->run()) {
			$this->session->forgotValidateCode = null;
			$post = $this->input->post();
			$user = User::where('email', $post['email'])->get_one();
			if (!$user) {
				return $this->validateError('user', '没有该email用户');
			}
			$user->update($user['id'], [
				'password' => password_hash($post['newPassword'], PASSWORD_DEFAULT)
			]);

			return $this->success();
		} else {
			return $this->validateError($this->form_validation->error_array());
		}
	}

	// 发送验证码邮件
	public function send_email()
	{
		$email = $this->input->post('email');

		if (!preg_match('/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]{2,4}$/', $email)) {
			return $this->validateError('email', '邮箱格式不正确');
		}
		$code = mt_rand(1000, 9999);
		$result = Mail::send($email, '日出宝邮件验证', '您正在进行日出宝认证，验证码:'.$code);
		$this->session->forgotValidateCode = $code;
		if ($result) {
			return $this->success();	
		} else {
			return $this->error();
		}
		
	}
}